package com.fx.attendance.ai;

import cn.hutool.core.codec.Base64Encoder;
import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.fx.attendance.enums.ResultEnum;
import com.fx.attendance.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @program: springcloud-dependcies
 * @description: 人脸识别简易操作工具类
 * @author: xjr
 * @create: 2020-04-19 18:04
 **/
@Component
@Slf4j
public class AiFaceTemplate implements InitializingBean {
    @Autowired(required = false)
    AipFace aipFace;

    private final String IMAGE_TYPE="BASE64";

    private static final HashMap<String,String> ADD_USER_OPTIONS=new HashMap<>(4);

    private static final HashMap<String,String> SEARCH_USER_OPTIONS=new HashMap<>(3);

    private static final HashMap<String,String> CHECK_USER_OPTIONS=new HashMap<>(4);

    static {
        //初始化搜索map
        SEARCH_USER_OPTIONS.put("quality_control","LOW");
        SEARCH_USER_OPTIONS.put("liveness_control","NONE");
        SEARCH_USER_OPTIONS.put("match_threshold","85");
        //初始化添加map
        ADD_USER_OPTIONS.put("quality_control","LOW");
        ADD_USER_OPTIONS.put("liveness_control","NONE");
        ADD_USER_OPTIONS.put("action_type","REPLACE");
        //初始化比对map
        CHECK_USER_OPTIONS.put("quality_control","LOW");
        CHECK_USER_OPTIONS.put("liveness_control","NONE");
        CHECK_USER_OPTIONS.put("match_threshold","85");
    }

    /*public String addUser(MultipartFile file, User user) throws Exception {
        checkAip();
        ADD_USER_OPTIONS.put("user_info", "1");
        return this.aipFace.addUser(stream2Base64(file),IMAGE_TYPE,roleType.groupId,user.getUserName(),ADD_USER_OPTIONS).toString(2);
    }

    public String addUser(String base64Img) throws  Exception{
        checkAip();
        ADD_USER_OPTIONS.put("user_info", "1");
        return this.aipFace.addUser(base64Img,IMAGE_TYPE,roleType.groupId,user.getUserName(),ADD_USER_OPTIONS).toString(2);
    }*/

    public String compareWithTwoImh(String img1,String img2){
        MatchRequest req1 = new MatchRequest(img1, "BASE64");
        MatchRequest req2 = new MatchRequest(img2, "BASE64");
        ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
        requests.add(req1);
        requests.add(req2);
        JSONObject res = aipFace.match(requests);
        return res.toString(2);
    }

    /**
     *
     * @description 方法描述
     * @param base64FaceImg:  base64编码的人脸图像
     * @return 人脸检测结果
     * @author xiejiarong
     * @date 2020年04月27日 11:56
     */
    public String checkFace(String base64FaceImg){
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("face_field", "age");
        options.put("liveness_control", "LOW");
        return this.aipFace.detect(base64FaceImg,IMAGE_TYPE,options).toString(2);
    }

    /**
     *
     * @description 方法描述
     * @param file:
     * @return
     * @author xiejiarong
     * @date 2020年04月27日 15:29
     */
    public String searchFace(MultipartFile file) throws Exception {
        checkAip();
        return this.aipFace.search(stream2Base64(file),IMAGE_TYPE,"1",SEARCH_USER_OPTIONS).toString(2);
    }

    /**
     *
     * @description 方法描述 根据图片进行校验
     * @param file: 上传的图片
     * @return  校验结果
     * @author xiejiarong
     * @date 2020年04月27日 15:29
     */
    public String checkFace(MultipartFile file, String compareId) throws Exception{
        checkAip();
        CHECK_USER_OPTIONS.put("user_id",compareId);
        return this.aipFace.search(stream2Base64(file),IMAGE_TYPE,"1",CHECK_USER_OPTIONS).toString(2);
    }


    /**
     *
     * @description 方法描述 根据图片的base64字符串进行校验
     * @param base64Img: 上传的图片 base64编码
     * @param compareId 比对者ID
     * @return  校验结果
     * @author xiejiarong
     * @date 2020年04月27日 15:29
     */
    public String checkFace(String base64Img,String compareId) throws ApiException {
        checkAip();
        CHECK_USER_OPTIONS.put("user_id",compareId);
        return this.aipFace.search(base64Img,IMAGE_TYPE,"1",CHECK_USER_OPTIONS).toString(2);
    }

    public boolean deleteFace(String userId,String faceToken) throws Exception{
        checkAip();
        return this.aipFace.faceDelete(userId,"1",faceToken,null).toMap().get("error_code").equals(0);
    }

    private String stream2Base64(MultipartFile file) throws Exception {
        InputStream inputStream=file.getInputStream();
        byte[] strByte=new byte[inputStream.available()];
        inputStream.read(strByte);
        return Base64Encoder.encode(strByte);
    }

    public static String[] stream2Base64(MultipartFile file, MultipartFile file2) throws Exception {
        InputStream inputStream1=file.getInputStream();
        InputStream inputStream2=file2.getInputStream();
        byte[] strByte1=new byte[inputStream1.available()];
        byte[] strByte2=new byte[inputStream2.available()];
        inputStream1.read(strByte1);
        inputStream2.read(strByte2);
        String [] res=new String[2];
        res[0]= Base64Encoder.encode(strByte1);
        res[1]=Base64Encoder.encode(strByte2);
        return res;
    }


    private void checkAip() throws ApiException{
        if (this.aipFace==null){
            throw new ApiException(ResultEnum.CUSTOMFAILURE,"人脸识别服务暂时不可用,请联系管理员");
        }
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("人脸操作工具类初始化结束,注入人脸客户端信息：{}",aipFace);
    }
}
